package pt.mauromad.guias.controller.admin;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import pt.mauromad.guias.controller.BaseController;
import pt.mauromad.guias.dao.DomainDao;
import pt.mauromad.guias.utils.form.Action;

@Controller
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
@RequestMapping("/admin/domain")
public class AdminDomainController extends BaseController {
	@RequestMapping(value = "/all", method = RequestMethod.GET)
	public String list(Model model) {
		model.addAttribute("domainList", domainService.all());
		add(model, Action.createLink("new"));
		return "list/all-domains";
	}

	@RequestMapping(value = "", method = RequestMethod.GET)
	public String show() {
		return redirect("/admin/domain/%s", getDomain());
	}

	@RequestMapping(value = "/{domain}", method = RequestMethod.GET)
	public String show(Model model, @PathVariable DomainDao domain) {
		model.addAttribute("domain", domain);
//		add(model, Action.createLink("manage"));
		return "domain-details";
	}

//	@RequestMapping(value = "/{domain}", method = RequestMethod.POST, params = "action=manage")
//	public String manage(Model model, @PathVariable DomainDao domain) {
//		model.addAttribute("domain", domain);
//		add(model, Action.createLink("manage.save"));
//		return "domain-details";
//	}
//
//	@RequestMapping(value = "/{domain}", method = RequestMethod.POST, params = "action=manage.save")
//	public String manage(Model model, @Validated DomainBean bean, @PathVariable DomainDao domain) {
//		model.addAttribute("domain", domain);
//		add(model, Action.createLink("manage.save"));
//		return redirect("/admin/domain/%s", domain.getDomain());
//	}

	@RequestMapping(value = "/new", method = RequestMethod.GET)
	public String create(Model model) {
		model.addAttribute("editable", true);
		add(model, Action.createPost("save.new"));

		return "domain-form";
	}

	@RequestMapping(value = "/new", method = RequestMethod.POST, params = "action=save.new")
	public String createDomain(Model model, @RequestParam @NotNull @Pattern(regexp = "[a-z0-9](\\.[a-z0-9])?") String domain) {
		DomainDao dao = new DomainDao();
		dao.setDomain(domain);
		domainService.save(dao);
		return redirect("all");
	}
}